import { defineStore } from 'pinia';
import type { WebsiteConfig } from '@/stores/modules/webconfig/types.ts';
import { selectWebConfig } from '@/api/webconfig';

// 默认配置
const DEFAULT_CONFIG: WebsiteConfig = {
  id: 0,
  profileBackground: '',
  profileAvatar: '',
  homeCarouselImages: '[]',
  homeTitle: '',
  homeSubtitle: '',
  archiveCarouselImages: '[]',
  archiveTitle: '',
  archiveSubtitle: '',
  articleCarouselImages: '[]',
  articleTitle: '',
  articleSubtitle: '',
  timelineCarouselImages: '[]',
  timelineTitle: '',
  timelineSubtitle: '',
  changelogCarouselImages: '[]',
  changelogTitle: '',
  changelogSubtitle: '',
  categoryCarouselImages: '[]',
  categoryTitle: '',
  categorySubtitle: '',
};

const useWebConfigStore = defineStore('web-config', {
  state: (): WebsiteConfig => ({
    ...DEFAULT_CONFIG
  }),

  getters: {
    // 获取解析后的轮播图数组
    parsedHomeCarousel: (state): string[] => {
      try {
        return JSON.parse(state.homeCarouselImages);
      } catch {
        return [];
      }
    },
    parsedArchiveCarousel: (state): string[] => {
      try {
        return JSON.parse(state.archiveCarouselImages);
      } catch {
        return [];
      }
    },
    parsedTimelineCarousel: (state): string[] => {
      try {
        return JSON.parse(state.timelineCarouselImages);
      } catch {
        return [];
      }
    },
    parsedArticleCarousel: (state): string[] => {
      try {
        console.log(JSON.parse(state.articleCarouselImages));
        return JSON.parse(state.articleCarouselImages);
      } catch {
        return [];
      }
    },
    parsedChangelogCarousel: (state): string[] => {
      try {
        return JSON.parse(state.changelogCarouselImages);
      } catch {
        return [];
      }
    },
    parsedCategoryCarousel: (state): string[] => {
      try {
        return JSON.parse(state.categoryCarouselImages);
      } catch {
        return [];
      }
    },
    // 获取完整配置的副本
    configSnapshot: (state): WebsiteConfig => ({ ...state }),
  },

  actions: {
    // 初始化配置
    async initConfig() {
      // 这里替换为实际的 API 调用
      const result = await selectWebConfig();
      this.updateConfig(result.data);
    },

    // 更新整个配置
    updateConfig(newConfig: Partial<WebsiteConfig>) {
      Object.assign(this, newConfig);
    },

    // 重置为默认配置
    resetConfig() {
      Object.assign(this, DEFAULT_CONFIG);
    },

  },

  persist: {
    key: 'web-config',
    storage: localStorage,
  },
});

export default useWebConfigStore;
